// components/address-picker/address-picker.js
Component({
  properties: {
    // 组件标签
    label: {
      type: String,
      value: ''
    },
    // 占位符文本
    placeholder: {
      type: String,
      value: '请选择地址'
    },
    // 默认选中的地址代码
    defaultValue: {
      type: Object,
      value: null
    },
    // 省份名称（用于回显）
    province: {
      type: String,
      value: ''
    },
    // 城市名称（用于回显）
    city: {
      type: String,
      value: ''
    },
    // 区县名称（用于回显）
    district: {
      type: String,
      value: ''
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      value: false
    },
    // 是否必填
    required: {
      type: Boolean,
      value: false
    }
  },

  data: {
    // 地址数据
    addressData: [],
    // 选择器列数据（原生picker格式）
    pickerColumns: [],
    // 选择器值
    pickerValue: [0, 0, 0],
    // 当前选中的地址
    selectedAddress: null,
    // 显示文本
    selectedText: '',
    // 加载状态
    loading: false
  },

  lifetimes: {
    attached() {
      this.loadAddressData();
    }
  },

  observers: {
    'province, city, district': function(province, city, district) {
      // 当传入的省市区名称变化时，重新设置地址
      if (this.data.addressData && this.data.addressData.length > 0) {
        if (province || city || district) {
          this.setDefaultValueByName(province, city, district);
        }
      }
    }
  },

  methods: {
    // 加载地址数据
    async loadAddressData() {
      try {
        this.setData({ loading: true });
        console.log('开始加载地址数据');
        
        // 导入API方法
        const { getCity } = require('../../api/api.js');
        
        // 调用API获取地址数据
        const res = await getCity();
        console.log('API返回的完整数据:', res);
        console.log('API返回数据类型:', typeof res);
        console.log('API返回数据键:', Object.keys(res || {}));
        
        // 检查不同的数据结构可能性
        let addressData = null;
        if (res && res.data) {
          addressData = res.data;
          console.log('使用 res.data，省份数量:', addressData.length);
        } else if (res && Array.isArray(res)) {
          addressData = res;
          console.log('直接使用 res 数组，省份数量:', addressData.length);
        } else {
          console.error('无法识别的数据格式:', res);
          wx.showToast({
            title: '地址数据格式错误',
            icon: 'none'
          });
          return;
        }
        
        if (addressData && addressData.length > 0) {
          console.log('地址数据加载成功，省份数量:', addressData.length);
          console.log('第一个省份数据:', addressData[0]);
          const transformedData = this.transformAddressData(addressData);
          console.log('转换后的地址数据:', transformedData.slice(0, 2)); // 只打印前两个省份
          this.setData({ addressData: transformedData });
          
          // 初始化选择器列数据
          this.initPickerColumns();
          
          // 如果有默认值，设置默认选中
          if (this.properties.defaultValue) {
            this.setDefaultValue(this.properties.defaultValue);
          } else if (this.properties.province || this.properties.city || this.properties.district) {
            // 如果传递了省市区名称，根据名称查找并设置
            this.setDefaultValueByName(this.properties.province, this.properties.city, this.properties.district);
          }
        } else {
          console.error('地址数据为空或格式错误:', addressData);
          wx.showToast({
            title: '地址数据为空',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('加载地址数据失败:', error);
        wx.showToast({
          title: '加载地址数据失败',
          icon: 'none'
        });
      } finally {
        this.setData({ loading: false });
      }
    },

    // 转换地址数据格式
    transformAddressData(data) {
      return data.map(province => ({
        v: province.v,
        n: province.n,
        c: province.c.map(city => ({
          v: city.v,
          n: city.n,
          c: city.c.map(district => ({
            v: district.v,
            n: district.n,
            c: []
          }))
        }))
      }));
    },

    // 初始化选择器列数据
    initPickerColumns() {
      const { addressData } = this.data;
      console.log('初始化选择器列数据，地址数据:', addressData);
      
      if (!addressData || addressData.length === 0) {
        console.error('地址数据为空');
        return;
      }
      
      // 省份列 - 直接使用名称数组（微信小程序原生picker格式）
      const provinceColumn = addressData.map(item => item.n);

      // 城市列（默认第一个省份的城市）
      const firstProvince = addressData[0];
      const cityColumn = firstProvince ? firstProvince.c.map(item => item.n) : [];

      // 区县列（默认第一个城市的区县）
      const firstCity = firstProvince?.c[0];
      const districtColumn = firstCity ? firstCity.c.map(item => item.n) : [];

      console.log('省份列（前3个）:', provinceColumn.slice(0, 3));
      console.log('城市列（前3个）:', cityColumn.slice(0, 3));
      console.log('区县列（前3个）:', districtColumn.slice(0, 3));

      const finalColumns = [provinceColumn, cityColumn, districtColumn];
      console.log('最终选择器列数据（原生格式）:', finalColumns);

      this.setData({
        pickerColumns: finalColumns
      });
      
      console.log('设置后的pickerColumns:', this.data.pickerColumns);
    },

    // 设置默认值（通过ID）
    setDefaultValue(defaultValue) {
      const { addressData } = this.data;

      // 查找省份索引
      if (defaultValue.province_id) {
        const provinceIdx = addressData.findIndex(item => item.v === defaultValue.province_id);
        if (provinceIdx >= 0) {
          const province = addressData[provinceIdx];
          
          // 查找城市索引
          if (defaultValue.city_id) {
            const cityIdx = province.c.findIndex(item => item.v === defaultValue.city_id);
            if (cityIdx >= 0) {
              const city = province.c[cityIdx];
              
              // 查找区县索引
              if (defaultValue.district_id) {
                const districtIdx = city.c.findIndex(item => item.v === defaultValue.district_id);
                if (districtIdx >= 0) {
                  // 更新城市和区县列
                  const cityColumn = province.c.map(item => item.n);
                  const districtColumn = city.c.map(item => item.n);
                  
                  this.setData({
                    pickerColumns: [this.data.pickerColumns[0], cityColumn, districtColumn],
                    pickerValue: [provinceIdx, cityIdx, districtIdx]
                  });
                  this.updateSelectedAddress(provinceIdx, cityIdx, districtIdx);
                }
              }
            }
          }
        }
      }
    },

    // 设置默认值（通过名称）
    setDefaultValueByName(provinceName, cityName, districtName) {
      const { addressData } = this.data;
      
      if (!provinceName) return;

      // 查找省份索引
      const provinceIdx = addressData.findIndex(item => item.n === provinceName);
      if (provinceIdx >= 0) {
        const province = addressData[provinceIdx];
        let cityIdx = 0;
        let districtIdx = 0;

        // 查找城市索引
        if (cityName) {
          const foundCityIdx = province.c.findIndex(item => item.n === cityName);
          if (foundCityIdx >= 0) {
            cityIdx = foundCityIdx;
            const city = province.c[cityIdx];

            // 查找区县索引
            if (districtName) {
              const foundDistrictIdx = city.c.findIndex(item => item.n === districtName);
              if (foundDistrictIdx >= 0) {
                districtIdx = foundDistrictIdx;
              }
            }
          }
        }

        // 更新城市和区县列
        const cityColumn = province.c.map(item => item.n);
        const city = province.c[cityIdx];
        const districtColumn = city.c.map(item => item.n);

        this.setData({
          pickerColumns: [this.data.pickerColumns[0], cityColumn, districtColumn],
          pickerValue: [provinceIdx, cityIdx, districtIdx]
        });
        this.updateSelectedAddress(provinceIdx, cityIdx, districtIdx);
      }
    },


    // 选择器值变化
    onPickerChange(e) {
      const value = e.detail.value;
      console.log('选择器值变化:', value);
      this.setData({ pickerValue: value });
      this.updateSelectedAddress(value[0], value[1], value[2]);
      
      // 触发选择事件
      this.triggerEvent('change', {
        address: this.data.selectedAddress,
        text: this.data.selectedText
      });
    },

    // 列变化（实现三级联动）
    onColumnChange(e) {
      const { column, value } = e.detail;
      const { addressData, pickerColumns, pickerValue } = this.data;
      console.log('列变化:', { column, value, addressData: addressData.length });
      
      const newPickerValue = [...pickerValue];
      newPickerValue[column] = value;

      if (column === 0) {
        // 省份变化，更新城市和区县列
        const province = addressData[value];
        const cityColumn = province.c.map(item => item.n);
        
        const firstCity = province.c[0];
        const districtColumn = firstCity ? firstCity.c.map(item => item.n) : [];

        newPickerValue[1] = 0;
        newPickerValue[2] = 0;

        this.setData({
          pickerColumns: [pickerColumns[0], cityColumn, districtColumn],
          pickerValue: newPickerValue
        });
      } else if (column === 1) {
        // 城市变化，更新区县列
        const province = addressData[pickerValue[0]];
        const city = province.c[value];
        const districtColumn = city.c.map(item => item.n);

        newPickerValue[2] = 0;

        this.setData({
          pickerColumns: [pickerColumns[0], pickerColumns[1], districtColumn],
          pickerValue: newPickerValue
        });
      } else {
        // 区县变化
        this.setData({ pickerValue: newPickerValue });
      }
    },

    // 更新选中的地址
    updateSelectedAddress(provinceIndex, cityIndex, districtIndex) {
      const { addressData } = this.data;
      
      const province = addressData[provinceIndex];
      const city = province.c[cityIndex];
      const district = city.c[districtIndex];

      const selectedAddress = {
        province: province.n,
        city: city.n,
        district: district.n,
        province_id: province.v,
        city_id: city.v,
        district_id: district.v
      };

      // 清理文本，移除所有换行符、制表符和多余空格
      const selectedText = `${province.n} ${city.n} ${district.n}`
        .replace(/[\r\n\t]/g, '') // 移除换行符、回车符、制表符
        .replace(/\s+/g, ' ') // 将多个连续空格替换为单个空格
        .trim(); // 去除首尾空格

      this.setData({
        selectedAddress,
        selectedText
      });
    },

    // 重置选择
    reset() {
      this.setData({
        selectedAddress: null,
        selectedText: '',
        pickerValue: [0, 0, 0]
      });
    },

    // 获取选中的地址
    getSelectedAddress() {
      return this.data.selectedAddress;
    },

  }
});
